import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useUser } from '../contexts/UserContext';
import { Box, CircularProgress } from '@mui/material';

interface PrivateRouteProps {
  children: React.ReactNode;
  requiredRole?: 'admin' | 'user'; // 可选的角色要求
}

const PrivateRoute: React.FC<PrivateRouteProps> = ({ children, requiredRole }) => {
  const { currentUser, isLoading } = useUser();
  const location = useLocation();
  
  // 加载中状态
  if (isLoading) {
    return (
      <Box 
        sx={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '100vh' 
        }}
      >
        <CircularProgress />
      </Box>
    );
  }
  
  // 未登录，重定向到登录页面并传递当前位置
  if (!currentUser) {
    return <Navigate to="/login" replace state={{ from: location }} />;
  }
  
  // 如果路由需要特定角色，检查用户角色
  if (requiredRole && currentUser.role !== requiredRole) {
    // 重定向到首页
    return <Navigate to="/chat" replace />;
  }

  // 用户已认证且角色匹配，渲染子组件
  return <>{children}</>;
};

export default PrivateRoute; 